import axios from 'axios';
import { cons } from '~/plugins/Tools/utils/log';
import Config from '~/config';
let {
  Local,
} = Config;
const getUserInfo = '/' + Local.userInfo;
export const SetToken = (token) => {
  if (!process.browser) return;
  window.localStorage.setItem('user', JSON.stringify(token));
};

export const UnsetToken = () => {
  if (!process.browser) return;
  window.localStorage.clear();
  window.localStorage.setItem('logout', Date.now());
};

export const GetUserFromSession = async (req, redirect, route, appCode = 'safety') => {
  cons.l = '进入GetUserFromSession';
  if (!req.headers.cookie) {
    cons.lE = 'JESESSIONID! 不存在！';
    return '';
  }
  try {
    let json = await axios.get(Local.url + getUserInfo, {
      headers: {
        'cookie': req.headers.cookie.toString(),
      },
    });
    cons.l = JSON.stringify(json.data);
    let data = json.data;
    if (data.constructor === Object && typeof data.url === 'undefined') {
      return data;
    } else return '';
  } catch (err) {
    cons.lE = `java 服务器异常!
GET ${Local.url}/userInfo
${err}
`;
    return '';
  }
};

export const GetUserFromLocalStorage = async (store) => {
  if (store.state.USER.authUser) {
    return Object.assign({}, store.state.USER);
  } else {
    try {
      let json = await axios.get(Local.url + getUserInfo);
      let data = json.data;
      if (data.constructor === Object && typeof data.url !== 'undefined') {
        return data;
      } else return '';
    } catch (err) {
      cons.lE = `java 服务器异常!
GET ${Local.url}/userInfo
${err}
`;
      return '';
    }
  }
};
